<%--
  Created by IntelliJ IDEA.
  User: CBo
  Date: 2025/8/28
  Time: 15:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:include page="header.jsp"/>
<html>
<head>
    <title>Title</title>
    <style>
        .container {
            max-width: 1200px;
        }

        .search-card {
            margin-bottom: 20px;
        }

        .search-form {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            align-items: flex-end;
        }

        .search-field {
            flex: 1;
            min-width: 250px;
        }

        .action-buttons .btn {
            margin-right: 5px;
        }

        .table-responsive {
            min-height: 400px;
        }

        .card {
            --bs-card-border-width: 0;
        }

        .card-body {
            padding: 0;
        }

        .search-actions {
            display: flex;
            gap: 10px;
        }
    </style>
</head>
<body>
<div class="container py-4">
    <!-- 搜索区域 -->
    <div class="card search-card">
        <div class="card-body">
            <div class="search-form">
                <div class="search-field">
                    <label for="searchType" class="form-label">查询条件</label>
                    <select class="form-select" id="searchType">
                        <option value="all">全部专业</option>
                        <option value="code">按专业编号查询</option>
                        <option value="name">按专业名称查询</option>
                    </select>
                </div>

                <div class="search-field" id="codeField">
                    <label for="majorCode" class="form-label">专业编号</label>
                    <input type="text" class="form-control" id="majorCode" placeholder="输入专业编号">
                </div>

                <div class="search-field" id="nameField">
                    <label for="majorName" class="form-label">专业名称</label>
                    <input type="text" class="form-control" id="majorName" placeholder="输入专业名称">
                </div>

                <div class="search-actions">
                    <a id="selectSubject">
                        <button type="button" class="btn btn-primary" id="searchBtn">
                            <i class="bi bi-search"></i> 查询
                        </button>
                    </a>
                    <a id="resetSelect">
                        <button type="button" class="btn btn-outline-secondary" id="resetBtn">
                            <i class="bi bi-arrow-clockwise"></i> 重置
                        </button>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加按钮 -->
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5>专业列表</h5>
        <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addMajorModal">
            <i class="bi bi-plus-circle"></i> 添加专业
        </button>
    </div>

    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th>专业编号</th>
                        <th>专业名称</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="majorTableBody">
                    <c:set var="pageitem" scope="session" value="${page.items}"/>
                    <c:if test="${empty pageitem}">
                        <tr>
                            <td colspan="4" class="text-center">没有找到匹配的专业数据</td>
                        </tr>
                    </c:if>
                    <c:forEach items="${sessionScope.page.items}" var="subject" varStatus="status">
                        <tr>
                            <td>${(sessionScope.page.pageIndex-1)*sessionScope.page.pageSize+status.count}</td>
                            <td>${subject.id}</td>
                            <td>${subject.name}</td>
                            <td class="action-buttons">
                                <button class="btn btn-sm btn-outline-primary edit-btn" data-id="${subject.id}"
                                        id="editBtn">
                                    <i class="bi bi-pencil"></i> 修改
                                </button>
                                <button class="btn btn-sm btn-outline-danger delete-btn" data-id="${subject.id}" data-name="${subject.name}">
                                    <i class="bi bi-trash"></i> 删除
                                </button>
                            </td>
                        </tr>
                    </c:forEach>
                    </tbody>
                </table>
            </div>
            <!-- 分页 -->
            <jsp:include page="pagination.jsp"/>
        </div>
    </div>

</div>

<!-- 添加专业模态框 -->
<div class="modal fade" id="addMajorModal" tabindex="-1" aria-labelledby="addMajorModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addMajorModalLabel">添加专业</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addMajorForm">
                    <div class="mb-3">
                        <label for="newMajorName" class="form-label">专业名称</label>
                        <input type="text" class="form-control" id="newMajorName" required>
                    </div>
                    <div class="mb-3 form-check form-switch">
                        <label for="newMajorState" class="form-label">专业状态</label>
                        <input type="checkbox" class="form-check-input" id="newMajorState">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" id="cancelAddMajorBtn">取消</button>
                <button type="button" class="btn btn-primary" id="saveAddMajorBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑专业模态框 -->
<div class="modal fade" id="editMajorModal" tabindex="-1" aria-labelledby="editMajorModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editMajorModalLabel">编辑专业</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editMajorForm">
                    <input type="hidden" id="editMajorId">
                    <div class="mb-3">
                        <label for="editMajorName" class="form-label">专业名称</label>
                        <input type="text" class="form-control" id="editMajorName" required>
                    </div>
                    <div class="mb-3 form-check form-switch">
                        <label for="editMajorState" class="form-label">专业状态</label>
                        <input type="checkbox" class="form-check-input" id="editMajorState">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveEditMajorBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel"
     aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteConfirmModalLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>您确定要删除专业：<span id="deleteMajorName" class="fw-bold"></span> 吗？此操作不可逆。</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认删除</button>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script>
    const codeField = document.getElementById('codeField');//专业编号
    const nameField = document.getElementById('nameField');//专业名称
    let selectSubject = document.getElementById('selectSubject');//查询专业
    let resetSelect = document.getElementById('resetSelect')//重置
    let subjects = [];
    let currentSubjectId = null;

    function initPage() {
        // 默认隐藏查询字段
        toggleSearchFields();

        // 监听查询条件变化
        document.getElementById('searchType').addEventListener('change', toggleSearchFields);
        document.getElementById('editBtn').addEventListener('click', handleEdit);
    }

    // 根据选择的查询类型显示/隐藏字段
    function toggleSearchFields() {
        let searchType = document.getElementById('searchType').value;
        // 重置字段
        codeField.style.display = 'none';
        nameField.style.display = 'none';

        // 根据选择显示相应字段
        if (searchType === 'code') {
            codeField.style.display = 'block';
        }
        if (searchType === 'name') {
            nameField.style.display = 'block';
        }
    }

    // 处理查询
    function handleSearch() {
        let searchType = document.getElementById('searchType').value;
        let subjectId = document.getElementById('majorCode').value.trim();//查询的专业编号
        let subjectName = document.getElementById('majorName').value.trim();//查询的专业名称
        if (searchType === 'code' && subjectId !== null && subjectId !== "") {
            selectSubject.href = "./select?subjectId=" + subjectId + "";
        } else if (searchType === 'name' && subjectName !== null && subjectName !== "") {
            selectSubject.href = "./select?subjectName=" + subjectName + "";
        } else {
            selectSubject.href = "./select";
        }
    }

    // 重置查询
    function handleReset() {
        document.getElementById('searchType').value = 'all';
        document.getElementById('majorCode').value = '';
        document.getElementById('majorName').value = '';
        toggleSearchFields();
        resetSelect.href = "./select"
    }

    //保存添加
    function saveAdd() {
        let newName = document.getElementById('newMajorName').value.trim();
        let newCode = document.getElementById('newMajorState').checked;
        console.log(newName, newCode)
        if (newName === '' || newCode === '') {
            alert('请填写完整的信息');
            return;
        }
        $.ajax({
            url: './add',
            type: 'POST',
            data: {
                subjectName: newName,
                subjectState: newCode
            },
            dataType: 'json',
            success: function (data) {
                alert('添加成功');
                window.location.href = "./select";
            },
            error: function (xhr, status, error) {
                alert('添加失败');
            }
        })

    }

    //处理修改
    async function handleEdit(event) {
        currentSubjectId = event.currentTarget.getAttribute('data-id');
        subjects = await getAllSubjectInfo();
        console.log(currentSubjectId)
        let subject = subjects.find(s => s.id === parseInt(currentSubjectId));
        console.log(subject)
        if (subject) {
            document.getElementById('editMajorName').value = subject.name;
            if (subject.state) {
                document.getElementById('editMajorState').checked = true;
            } else {
                document.getElementById('editMajorState').checked = false;
            }
            const editModal = new bootstrap.Modal(document.getElementById('editMajorModal'));
            editModal.show();
        }
    }

    //保存修改
    function saveEdit() {
        console.log("保存修改")
        let subjectId = currentSubjectId;
        console.log(subjectId)
        let subjectName = document.getElementById('editMajorName').value;
        let subjectState = document.getElementById('editMajorState').checked;
        console.log(subjectState)
        $.ajax({
            type: "POST",
            url: "./update",
            data: {
                subjectId: subjectId,
                subjectName: subjectName,
                subjectState: subjectState
            },
            dataType: "json",
            success: function (data) {
                console.log(data)
                const editModal = bootstrap.Modal.getInstance(document.getElementById('editMajorModal'));
                editModal.hide();
                alert('修改成功')
                // 重定向到查询页面
                window.location.href = "./select";
            },
            error: function (xhr, status, error) {
                console.log(error);
            }
        })
    }

    //查询所有专业
    const getAllSubjectInfo = function () {
        return new Promise((resolve, reject) => {
            $.ajax({
                type: "GET",
                url: "./allsubjectinfo",
                dataType: "json",
                success: resolve,
                error: reject
            })
        })
    }

    //处理删除
    function handleDelete(event) {
        let subjectId = event.currentTarget.getAttribute('data-id');
        let subjectName = event.currentTarget.getAttribute('data-name');
        console.log(subjectId,subjectName)
        const deleteModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
        document.getElementById('deleteMajorName').innerText = subjectName;
        deleteModal.show();
        document.getElementById('confirmDeleteBtn').addEventListener('click',function () {
            $.ajax({
                type: "GET",
                url: "./delete",
                data: {
                    subjectId: subjectId
                },
                dataType: "json",
                success: function (data) {
                    console.log(data)
                    const deleteModal = bootstrap.Modal.getInstance(document.getElementById('deleteConfirmModal'));
                    deleteModal.hide();
                    alert('删除成功');
                    window.location.href = "./select";
                },
                error: function (xhr, status, error) {
                    alert('删除失败');
                    console.log(error);
                }
            })

        })
    }

    //添加 取消时清空表单
    function handleCancel() {
        document.getElementById('newMajorName').value = '';
        document.getElementById('newMajorState').checked = false;
    }


    //初始化事件监听
    document.getElementById('searchBtn').addEventListener('click', handleSearch);
    document.getElementById('resetBtn').addEventListener('click', handleReset);
    document.querySelectorAll('.edit-btn').forEach(editBtn => {
        editBtn.addEventListener('click', handleEdit);
    })
    document.getElementById('saveEditMajorBtn').addEventListener('click', saveEdit);
    document.getElementById('saveAddMajorBtn').addEventListener('click', saveAdd);
    document.querySelectorAll('.delete-btn').forEach(deleteBtn => {
        deleteBtn.addEventListener('click', handleDelete);
    })
    document.getElementById('cancelAddMajorBtn').addEventListener('click', handleCancel);
    //初始化页面
    initPage();
</script>
</body>
</html>
<jsp:include page="footer.jsp"/>